package com.power.web.district;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;

import com.power.Constants;
import com.power.model.district.TsDistrict;
import com.power.model.user.TsSysuser;
import com.power.services.district.TsDistrictService;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.PingYinUtil;
import com.power.util.RequestUtil;
import com.power.web.action.base.AbstractBaseAction;

public class TsDistrictAction extends AbstractBaseAction {

	private static final long serialVersionUID = 4628301066492657392L;
	private String jsonString;
	@Autowired
	private TsDistrictService service;

	private TsDistrict district;

	@SuppressWarnings("unchecked")
	public String buildDistrict46JSONString() {
		try {
			int start = this.start;
			int limit = this.limit;
			if (limit == 0)
				limit = 20;
			String disName = CharacterUtil.encode(RequestUtil.getParam(request,
					"disName", ""));
			Integer pid = RequestUtil.getParam(request, "pid", -1);
			Map<String, Object> map = this.service.findAll(disName, start,
					limit, pid);
			List<TsDistrict> list = (List<TsDistrict>) map.get("data");
			int count = new Integer(map.get("count").toString());
			StringBuffer _JSONStr = null;
			String callback = this.callback;
			_JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("({\"total\":").append(count)
					.append(",\"results\":");
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor("inputDate",
					new DateJsonValueProcessor("yyyy-MM-dd kk:mm:ss"));
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			JSONArray jsonObject = JSONArray.fromObject(list, cfg);
			_JSONStr.append(jsonObject.toString());
			_JSONStr.append("})");
			jsonString = _JSONStr.toString();
		} catch (Exception e) {
			log.error("加载地区列表出错", e);
			this.jsonString = "[]";
		}
		return Constants.JSONSTRING_RESULT_NAME;
	}

	public String save() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		try {
			if (null != district) {
				TsSysuser user = (TsSysuser) this.session
						.get(Constants.USERINFO_KEY);
				district.setInputDate(DateTimeUtil.getCurrentDateTime());
				district.setInputMan(user.getUsername());
				district.setInputManId(user.getId());
				district.setFirstChar(PingYinUtil.getPingYin(
						district.getName(), 2, 1).substring(0, 1));
				Integer num = service.saveOrUpdate(district);
				if(num==1){
					this.response.getWriter().print("{success:false,msg:'编码或地区名称已经存在!'}");
					return null;
				}
			}
			this.response.getWriter().print("{success:true,msg:'保存成功!'}");
		} catch (Exception e) {
			log.error("地区保存失败", e);
			try {
				this.response.getWriter().print("{success:false,msg:'保存失败!'}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String delete() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		String ids = RequestUtil.getParam(request, "ids", "");
		try {
			service.delete(ids);
			this.response.getWriter().print("{success:true,msg:'删除成功!'}");
		} catch (Exception e) {
			try {
				if ("1".equals(e.getMessage())) {
					this.response.getWriter().print(
							"{success:false,msg:'请先删除省级下面的市级信息,删除失败!'}");
				} else {
					log.error("地区保存失败", e);
					this.response.getWriter().print(
							"{success:false,msg:'删除失败!'}");
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public String loadDistrict() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Integer pid = RequestUtil.getParam(this.request, "pid", -1);
			List list = service.loadByPid(pid);
			String callback = RequestUtil.getParam(this.request, "callback",
					"callback");
			StringBuffer _JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("([");
			for (int i = 0; i < list.size(); ++i) {
				TsDistrict obj = (TsDistrict) list.get(i);
				_JSONStr.append("[\"").append(obj.getId()).append("\",");
				_JSONStr.append("\"").append(obj.getName()).append("\"],");
			}
			if (list.size() > 0)
				_JSONStr.deleteCharAt(_JSONStr.lastIndexOf(","));
			_JSONStr.append("])");
			this.jsonString = _JSONStr.toString();
			out.print(this.jsonString);
		} catch (Exception e) {
			log.error("加载地区出错", e);
			out.print("[]");
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public String buildJsonData4Page() {
		try {
			Integer pid = RequestUtil.getParam(this.request, "pid", -1);
			String jsonString = "[{";
			jsonString += "\"result\" : ";
			List list = service.loadByPid(pid);
			if (null == list)
				list = new ArrayList();
			jsonString += "'[";
			for (int num = 0; num < list.size(); num++) {
				TsDistrict data = (TsDistrict) list.get(num);
				Integer code = data.getId();
				String name = data.getName();
				if (num != 0)
					jsonString += ",";
				jsonString += "{\"code\":\"" + code + "\",\"name\":\"" + name
						+ "\"}";
			}
			jsonString += "]'";
			jsonString += "}]";
			this.response.reset();
			this.response.setCharacterEncoding("UTF-8");
			this.response.getWriter().print(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("输出JSON数据错误！", e);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public String loadDistrictSelect() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Integer pid = RequestUtil.getParam(this.request, "pid", -1);
			List<TsDistrict> list = service.loadByPid(pid);
			JSONArray jsonArry = JSONArray.fromObject(list);
			this.jsonString = jsonArry.toString();
			out.print(this.jsonString);
		} catch (Exception e) {
			log.error("加载地区出错", e);
			out.print("[]");
		}
		return null;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public TsDistrict getDistrict() {
		return district;
	}

	public void setDistrict(TsDistrict district) {
		this.district = district;
	}

}
